/**
 * Created by 2006-1-30 0:03:28
 * $Id: InitServlet.java 53 2006-06-28 15:52:26Z wjx $
 */
package com.someok.web.servlet;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.app.Velocity;

import com.someok.base.Config;
import com.someok.utils.PropertiesUtil;
import com.someok.utils.template.TemplateContext;
import com.someok.utils.template.TemplateUtil;


/**
 *
 *
 * <p>
 * <a href="InitServlet.java.html"><i>View Source</i></a>
 * </p>
 *
 * @author wjx
 * @version $Revision: 53 $ $Date: 2006-06-28 23:52:26 +0800 (星期三, 28 六月 2006) $
 *
 * @web.servlet name = "Init Servlet" load-on-startup="10"
 * @web.servlet-mapping url-pattern = "/InitApp"
 */
public class InitServlet extends BaseServlet {


	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(InitServlet.class);

	private static final long serialVersionUID = -2121403521191733958L;

	private static final String FILE_RESOURCE_LOADER_PATH = "file.resource.loader.path";
	private static final String RUNTIME_LOG = Velocity.RUNTIME_LOG;

	/**
	 * log日志输出文件所在目录的前缀（为应用的跟目录）.<br>
	 * 缺省值为someok，如：${someok}/logs/out.log.
	 */
	private String webRootPath;

	/**
	 *
	 */
	public void init() throws ServletException {
		System.setProperty("ctxPath", getWebAppBasePath());
		initVelocity();
	}

	/**
	 * 初始化Velocity.
	 */
	public void initVelocity() {
		// 初始化Velocity
		Properties veProp = null;

		try {
			URL url = getClass().getResource("/velocity.properties");
			veProp = PropertiesUtil.createFromFile(new File(url.toURI()));

			// 设置 velocity 的 file.resource.loader.path 属性
			if (logger.isDebugEnabled()) {
				logger.debug("init() - Velocity Init Path : "
						+ veProp.getProperty(FILE_RESOURCE_LOADER_PATH));
			}
			String veResourceLoaderPath = veProp.getProperty(FILE_RESOURCE_LOADER_PATH);

			webRootPath = getWebAppBasePath();
			if (webRootPath.endsWith("/")) {
				webRootPath = StringUtils.chop(webRootPath);
			}
			if (!veResourceLoaderPath.startsWith("/")) {
				veResourceLoaderPath = File.pathSeparator + veResourceLoaderPath;
			}
			veResourceLoaderPath = new File(webRootPath + veResourceLoaderPath).getCanonicalPath();
			veProp.setProperty(FILE_RESOURCE_LOADER_PATH, veResourceLoaderPath);

			// 设置 velocity 的 log 文件 "runtime.log"
			String veRuntimeLog = veProp.getProperty(RUNTIME_LOG);
			if (!veRuntimeLog.startsWith("/")) {
				veRuntimeLog = File.pathSeparator + veRuntimeLog;
			}
			veRuntimeLog = new File(webRootPath + veRuntimeLog).getCanonicalPath();
			veProp.setProperty(RUNTIME_LOG, veRuntimeLog);

			// 初始化 Velocity
			Velocity.init(veProp);

			if (logger.isDebugEnabled()) {
				logger.debug("init() - Velocity Converted Path : "
						+ Velocity.getProperty(FILE_RESOURCE_LOADER_PATH));
			}
		} catch (IOException e) {
			logger.error("init()", e);
			throw new RuntimeException(e);
		} catch (Exception e) {
			logger.error("init()", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 *
	 */
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		setCharacterEncoding(response);

		PrintWriter out = response.getWriter();

		TemplateContext context = new TemplateContext();
		context.put("webRootPath", webRootPath);

		String vmFile = Config.getInstance().getString("servlet.init");
		logger.debug("service() - vmFile : " + vmFile);

		out.println(TemplateUtil.merge(context, vmFile));
	}


	protected String outputPageBody(HttpServletRequest request,
			HttpServletResponse response) {
		TemplateContext context = new TemplateContext();
		context.put("webRootPath", webRootPath);

		String vmFile = Config.getInstance().getString("servlet.init");
		logger.debug("service() - vmFile : " + vmFile);

		return TemplateUtil.merge(context, vmFile);
	}

}
